package zhaixf.fx.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import zhaixf.fx.DAO.PassDAO;
import zhaixf.fx.DAO.RecordDAO;
import zhaixf.fx.DAO.ToolDAO;
import zhaixf.fx.been.Record;
import zhaixf.fx.been.Tool;

import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class ToolService {
    @Autowired
    private ToolDAO toolDAO;
    @Autowired
    private PassDAO passDAO;
    @Autowired
    private RecordDAO recordDAO;

    public String getToolStatusById(String id){
        return toolDAO.queryById(id).getStatus();
    }

    public Tool getToolById(String id){
        return toolDAO.queryById(id);
    }


    @Transactional
    public String baoxiu(Tool tool, String pass, String bz){
        //检验密码
        String password = passDAO.queryByName("报修");
        if (pass != null && password.equals(pass)) {
            return main("报修", tool , bz);

        } else {
            return "口令错误";
        }
    }

    @Transactional
    public String weixiu(Tool tool, String pass, String bz){
        //检验密码
        String password = passDAO.queryByName("维修");
        if (pass != null && password.equals(pass)) {
            return main("维修", tool, bz);

        } else {
            return "口令错误";
        }
    }

    private String main(String tag, Tool tool, String bz){
        try{
            String nowtime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());//设置日期格式
            //tool
            tool.setUptime(nowtime);
            //record
            Record record = new Record();
            record.setToolid(tool.getId());
            record.setUptime(nowtime);
            if (null != bz && "".equals(bz)) {
                record.setBeizhu(bz);
            }

            switch (tag){
                case "报修":
                    //tool
                    tool.setStatus("故障");
                    //record
                    record.setType("报修");
                    record.setTrouble(tool.getTrouble());
                    break;
                case "维修":
                    //tool
                    tool.setStatus("正常");
                    tool.setTrouble("-");
                    //record
                    record.setType("修复");
                    record.setTrouble("-");
                    break;
            }

            //修改设备状态
            toolDAO.updateForBx(tool);
            //添加record记录
            recordDAO.addRecord(record);
            return "修改成功";

        }catch (Exception e){
            System.out.println(e.getMessage());
            return "系统异常";
        }
    }
}
